<script>
import {defineComponent} from 'vue'
import {handleSuccess,handleError} from "@/util/request";
import {useRouter} from "vue-router/composables";
import router from "@/router";

export default defineComponent({

  name: "LoginPage",
  data(){
    return{
      user:{
        //绑定当前登录的用户
        account: 'zhangsan111',
        password: '1234'
      },
      rules: {
        account: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
    }
  },
  methods:{
    goToRegister() {
      this.$router.push('/user/register');
    },
    submitForm(forName){
      this.$refs[forName].validate((valid)=>{
        if (valid){
          this.$http.post('/user/login',this.user)
              .then((result)=>{
            //先把result打印出来看看
                const user=handleSuccess(result)

                if (user){
                  localStorage.setItem('user',JSON.stringify(user))

                  this.$router.replace('/')
                }

          })
              .catch((error)=>{
               handleError(error)
              })
        }
      })
    },

  },
   goToRegister() {
      router.push('/user/register')
    }
})
</script>

<template>
  <div class="bg">
    <div class="login-box">
      <div class="login-title">在线学术社区系统</div>
      <el-form ref="form" :model="user" :rules="rules" class="login-form">
        <el-form-item prop="account">
          <el-input placeholder="请输入账户名" v-model="user.account">
            <template slot="prepend">
              <div class="el-icon-user-solid"></div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" v-model="user.password" @keyup.enter.native="submitForm('form')"  show-password>
            <template slot="prepend">
              <div class="el-icon-lock"></div>
            </template>
          </el-input>
        </el-form-item>
        <div style="display: flex; justify-content: space-between">
          <el-button type="primary" @click="submitForm('form')" >登录</el-button>
          <el-button @click="goToRegister">注册账号</el-button>
          <el-button @click="">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.bg {
  height: 100vh;
  background-color: whitesmoke;
}

.login-box {
  width: 550px;
  padding: 50px;
  background-color: #92b6d5;
  border-radius: 10px;
  box-shadow: 0 0 10px gray;
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

.login-form {
  width: 74%;
  margin: auto;
}

.login-title {
  padding-bottom: 30px;
  text-align: center;
  font-weight: 600;
  font-size: 20px;
  color: whitesmoke;
  cursor: pointer;
}
</style>